Ext.define('Gigi.controller.Users',
		{
			extend : 'Ext.app.Controller',

			views : [ 'user.List', 'user.Edit' ],
			stores : [ 'Users' ],
			models : [ 'User' ],

			init : function() {
				this.control({
					'#add' : {
						click : this.onAddClick
					},
					'#delete' : {
						click : this.onDeleteClick
					},
					'#update' : {
						click : this.onUpdateClick
					},
					'useredit button[action=save]' : {
						click : this.onEditSaveClick
					}
				});
			},

			onAddClick : function(button) {
				Ext.create('widget.useredit', {
					title : '新增用户'
				});
			},

			onDeleteClick : function(button) {
				var grid = button.up('gridpanel'), selModel = grid
						.getSelectionModel();
				if (selModel.getCount() != 1) {
					Ext.Msg.show({
						title : '删除用户信息',
						msg : '请选择一条记录',
						icon : Ext.MessageBox.ERROR,
						buttons : Ext.MessageBox.OK
					});
				} else {
					Ext.Msg.show({
						title : '删除用户',
						msg : '您确认删除吗？',
						icon : Ext.MessageBox.QUESTION,
						fn : function(btn) {
							if (btn == "ok") {
								selModel.getSelection()[0].destroy({
									success : function() {
										Ext.MessageBox.alert('删除用户', '删除成功！');
										grid.getStore().load();
									},
									failure : function(response, opts) {
										Ext.MessageBox.alert('删除用户',
												response.responseText);
									}
								});
							}
						},
						buttons : Ext.MessageBox.OKCANCEL
					});
				}
			},

			onUpdateClick : function(button) {
				var grid = button.up('gridpanel'), selModel = grid
						.getSelectionModel();
				if (selModel.getCount() != 1) {
					Ext.Msg.show({
						title : '修改用户信息',
						msg : '请选择一条记录',
						icon : Ext.MessageBox.ERROR,
						buttons : Ext.MessageBox.OK
					});
				} else {
					var win = Ext.widget('useredit', {
						title : '修改用户',
						actionType : 'update'
					});
					var form = win.down('form');
					var user = Ext.ModelManager.getModel('Gigi.model.User');
					user.load(selModel.getSelection()[0].get('username'), {
						success : function(user) {
							form.loadRecord(user);
						}
					});

				}
			},

			onEditSaveClick : function(button) {
				var win = button.up('window'), form = win.down('form')
						.getForm(), userlist = Ext.ComponentQuery
						.query('userlist')[0];
				if (form.isValid()) {
					var user = Ext.create('Gigi.model.User', form.getValues());
					var operation = win.actionType;
					//如果是新增，将Model的phantom设置成true,表示是新对象。
					if (operation == 'create') {
						user.phantom = true;
					} else {
						user.phantom = false;
					}
					user.save({
						success : function(record, operation) {
							Ext.MessageBox.alert('保存用户', '保存成功！');
							win.close();
							userlist.getStore().load();
						},
						failure : function(record, operation) {
							Ext.MessageBox.alert('保存用户', '保存用户失败！');
						}
					});
				}
				;
			}
		});